package com.fingard.dsp.bank.directbank.klb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;


public class KLB01Transaction extends KLB01Base implements ITransaction {

    // 采用流处理方式
    // 1、循环调用readRecord()读取一个请求明细，然后写入发银行的XML对象
    // 2、发银行
    // 3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
    // 然后调用writeRetDetail()，写入返回ATS的明细
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        // TODO Auto-generated method stub
        // 历史明细查询返回ATS的对象

        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();// 写返回ATS的统一头部信息
        try {
            bnkVersion = "0.0.0.1";
            bank = "KLB";
            bnkOrgId = bankFront.corpNo;
            bnkoOrgName = bankFront.org;
            bnkTxCode = "8865";
            bnkTxPackNo = p_req7516.reqHeader.transSeqID;
            // tmpClndrStepTo.get(Calendar.MONTH) MONTH是从0开始编的，意味着0是1月，11是12月
            Calendar tmpCalendarFrom = Calendar.getInstance(); // 使用默认时区和语言环境这种方法获得一个日历。
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpNowStartRecord = 0;// 总条数
            int intPageNumber = 1;// 页码数 默认查询第一页
            int tmpNowReadedCount = 0;// 已读条数

            boolean tmpQryNext = true;
            // 分页查询
//			while (tmpQryNext && tmpRespCode.length() == 0) {
            XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
            // 写入通用的头部节点

            writeCommonHeader(xmlWriter);
            xmlWriter.writeStartElement("body");
            xmlWriter.writeElementString("Flag", "2");// Flag 查询标志
            // 1-最近十笔明细查询;2-按日期查询;3-当月查询;4-按交易金额区间查询
            xmlWriter.writeElementString("AccNo", p_req7516.actNum);// AccNo
            // 帐号/卡号
            xmlWriter.writeElementString("SubAcct", " ");// SubAcct 款项代码
            // 空查询基本款项或主款项
            xmlWriter.writeElementString("BeginDate", Format.Date10Format.format(tmpCalendarFrom.getTime()));// BeginDate
            // 起始日期
            // 查询标志为2时必输

            xmlWriter.writeElementString("EndDate", Format.Date10Format.format(tmpCalendarTo.getTime()));// EndDate
            // 终止日期
            // 查询标志为2时必输
            xmlWriter.writeElementString("Ccy", "01");// Ccy 币种
            // 01-人民币;12-英镑;13-港币;14-美元;27-日元;38-欧元

            xmlWriter.writeElementString("Amt1", " ");// Amt1 金额上限 查询标志为4时必输
            xmlWriter.writeElementString("Amt2", " ");// Amt2 金额下限 查询标志为4时必输
            xmlWriter.writeElementString("PrintFlag", " ");// PrintFlag
            // 数据排序标志 1-升序
            // 2-降序，不上送时保持原有排序方式

            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            XmlTextReader tmpBkReader;
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String returnCode = tmpBkReader.getFirstText("/root/head/RetCode");
                    String returnMsg = tmpBkReader.getFirstText("/root/head/RetMsg");
                    tmpRespCode = "0";
                    tmpRespInfo = returnMsg;
                    if ("000000".equals(returnCode) || "M0001".equals(returnCode)) {
                        int tmpTotalRocords = 0;// 总条数
                        tmpTotalRocords = Integer.parseInt(tmpBkReader.getFirstText("/root/body/Num"));
                        int tmpEachPiCount = 0;
                        if (tmpTotalRocords > 0) {
                            while (tmpBkReader.read("/root/body/records/rd")) {
                                tmpEachPiCount++;
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                tmpRetDetail.cdFlag = tmpBkReader.readedXElement.getSingleText("CDFlag");// 借贷标记
                                tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("acctno");
                                tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("OppAccountNo");
                                tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("OppAccName");
                                if (("C").equals(tmpRetDetail.cdFlag)) {
                                    tmpRetDetail.cdFlag = "2";
                                } else {
                                    tmpRetDetail.cdFlag = "1";
                                }
                                tmpRetDetail.tranAmt = tmpBkReader.readedXElement.getSingleText("TranAmt");// 交易金额
                                tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("Bal").trim();// 余额
                                String tranDate = tmpBkReader.readedXElement.getSingleText("TranDate");// yyyy-MM-dd
                                // 交易时间
                                // 系统格式为yyyy-MM-dd
                                // hh:mm:ss
                                String tranTime = tmpBkReader.readedXElement.getSingleText("TransTime");// hh:mm:ss
                                tmpRetDetail.tranDate = tranDate;
                                tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tranTime.substring(11, 19).replace(".", ":");
                                tmpRetDetail.valueDate = tmpRetDetail.tranDate;// 起息日没有返回就用交易日
                                tmpRetDetail.abstr = tmpBkReader.readedXElement.getSingleText("Memo");
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        }
                        tmpNowReadedCount += tmpEachPiCount;// 总记录数
                        if (tmpNowReadedCount < tmpTotalRocords)// 查询下一页
                        {
                            intPageNumber = intPageNumber + 1;// 页码加一 查询第二页
                            tmpNowStartRecord = tmpNowReadedCount + 1;// 记录已经查询的记录个数
                        } else if (tmpNowReadedCount == tmpTotalRocords)// 本次分页查询完毕
                        {
                            tmpQryNext = false;
                            tmpNowStartRecord = 0;
                            tmpNowReadedCount = 0;
//                                continue;
                        }
                    } else {
//                            break;
                    }
                } else {
                    tmpQryNext = false;
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpSbMsg.toString();
//						break;
                }
            } else {
                tmpQryNext = false;
                tmpRespCode = "-1";
                tmpRespInfo = tmpStrRet[1];
//					break;
            }

//			}

        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
            WriteBankLogLn(e);
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();// 写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        // TODO Auto-generated method stub
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }

}
